<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="业务分组" prop="groupName">
        <el-select v-model="form.groupName" default-first-option filterable allow-create clearable placeholder="请选择">
          <el-option v-for="item,index in groups" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="业务KEY" prop="viewKey">
        <el-input v-model="form.viewKey" placeholder="请输入" @blur="$emit('changeViewKey',form.viewKey)"></el-input>
      </el-form-item>
       <el-form-item label="业务名称" prop="viewName">
        <el-input v-model="form.viewName" placeholder="请输入" @blur="$emit('changeViewName',form.viewName)"></el-input>
      </el-form-item>
      <el-form-item label="业务描述" prop="remark">
        <el-input type="textarea" v-model="form.remark" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="模式" prop="viewType">
        <el-radio-group v-model="form.viewType" @change="(e)=>{$emit('changeViewType',e)}" size="mini">
          <el-radio-button label="1">列表</el-radio-button>
          <el-radio-button label="2">表单</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <div style="color: red;margin:40px;">请选择关联表单后再设置其他栏目，改动将清空其他栏目填写的信息，请谨慎操作</div>
      <el-form-item label="关联主表" prop="formKey">
        <el-select v-model="form.formKey" @change="getColumns" placeholder="请选择">
          <el-option v-for="item,index in formList" :key="index" :label="item.name" :value="item.formKey"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="附加表" prop="extraForms" v-if="form.formKey">
        <div v-for="item,index in extraForms" :key="index" class="extra">
          <div class="extra-forms">
            附加表{{index+1}}：
            <el-select v-model="item.formKey" @change="(e)=>{getColumns(e,index)}" placeholder="请选择">
              <el-option v-for="ite,inde in formList" v-show="!isSelect(ite.formKey)" :key="inde" :label="ite.name"
                :value="ite.formKey"></el-option>
            </el-select>
            <span>关联到：</span>
            <el-select v-model="item.bindFormKey" @change="(e)=>{getColumns(e,index)}" placeholder="请选择">
              <el-option v-for="ite,inde in formList" v-show="ite.formKey!=item.formKey&&isSelect(ite.formKey)"
                :key="inde" :label="ite.name" :value="ite.formKey"></el-option>
            </el-select>
            <i class="el-icon-remove-outline my-icon" @click="delExtra(index)"style="color: red;"></i>
            <span class="develop" v-if="item.relevanceSchema.body[0].fields.length" @click="item.develop=!item.develop">
              {{item.develop?'收起配置':'显示配置'}}
            </span>
          </div>
          <div v-show="item.develop">
            <div v-if="item.formKey&&item.bindFormKey">
              关联关系：
              <preview ref="relevance" v-if="item.relevanceSchema.body[0].fields.length" :previewConfig="{schema:item.relevanceSchema}" />
            </div>
            <div v-if="item.formKey&&item.bindFormKey">
              查询条件(选填)：
              <preview ref="conditions" v-if="item.conditionSchema.body[0].fields.length" :previewConfig="{schema:item.conditionSchema}" />
            </div>
          </div>
        </div>
        <i class="el-icon-circle-plus-outline my-icon" @click="addExtra(true)" v-show="extraForms.length<formList.length-1" style="color: #409eff;"/>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    details
  } from "@/api/tool/formManage";
  import preview from "@/views/tool/view/index.vue";
  import {getConditionsFields} from "@/utils/amisUtil.js";
  export default {
    name: 'basic',
    components: {
      preview
    },
    props: {
      formKey: {
        type: String,
        defulat: ''
      },
      formList: {
        type: Array,
        defulat: () => []
      },
      basic: {
        type: Object,
        defulat: () => null
      },
      groups: {
        type: Array,
        default: ()=>[],
      }
    },
    data() {
      var validExtraForms = (rule, value, callback) => {
        this.extraFormValues.some((item,index)=>{
          if(!item.formKey||!item.bindFormKey||!item.relevance||!Object.keys(item.relevance).length){
            callback(new Error('请完善附加表'+(index+1)));
            return true
          }
        })
        callback();
      };
      return {
        form: {
          groupName: undefined,
          viewKey: undefined,
          viewName: undefined,
          remark: undefined,
          viewType: 1,
          formKey: undefined,
        },
        extraForms: [],//附加表配置
        extraFormValues: [],//附加表最终提交数据
        formKeyColumns: {},
        primaryKeyFieldObj: {},//表的主键
        rules: {
          groupName: [{
            required: true,
            message: '请选择业务分组',
            trigger: 'blur'
          }],
          viewKey: [{
            required: true,
            message: '请输入业务KEY',
            trigger: 'blur'
          }],
          viewName: [{
            required: true,
            message: '请输入业务名称',
            trigger: 'blur'
          }],
          formKey: [{
            required: true,
            message: '请选择关联表单',
            trigger: 'change'
          }],
          extraForms:[
              { validator: validExtraForms }
          ]
        }
      };
    },
    computed: {
      isSelect() {
        return (formKey) => {
          return this.extraForms.some(item => {
            return this.form.formKey == formKey || item.formKey == formKey
          })
        }
      }
    },
    created() {
      setTimeout(()=>{
        if (this.formKey) {
          this.form.formKey = this.formKey
          this.getColumns(this.formKey)
        }
        if (this.basic) {
          this.form = this.basic
          if(!this.basic.extraForms){
            this.basic.extraForms=[]
          }
          setTimeout(()=>{
            this.basic.extraForms.forEach((item,index)=>{
                this.addExtra(false)//添加附件表
                this.$nextTick(()=>{
                  this.getColumns(item.formKey,index,item)
                })
            })
          },300)
        }
      },500)
    },
    methods: {
      //获取表单字段
      getColumns(formKey,index,extraData) {
        if(index===undefined){
          //主表变化
          this.extraForms=[]
        }
        if (this.formKeyColumns[formKey]) {
         if(index===undefined){
           this.setFormKeyAndColumns()
         }else{
           this.extraChange(formKey,index,extraData)
         }
        } else {
          details(formKey).then(res => {
            if (res.code == 200) {
              this.formKeyColumns[formKey] = []
              if(res.data){
                this.primaryKeyFieldObj[formKey]=res.data.primaryKeyField//表的主键
                this.formKeyColumns[formKey] = res.data.columns.map(item=>{
                  item.columnName=formKey+'__'+item.columnName
                  return item
                })
              }
              if(index===undefined){
                this.setFormKeyAndColumns()
              }else{
                this.extraChange(formKey,index,extraData)
              }
            }
          })
        }
      },
      //附表变化  extraData编辑时回显数据
      extraChange(formKey,index,extraData){
        this.extraForms[index].relevanceSchema.body[0].fields=[]
        this.extraForms[index].conditionSchema.body[0].fields=[]
        let extraForm=this.extraForms[index]
        if(extraData){
          extraForm.formKey=extraData.formKey
          extraForm.bindFormKey=extraData.bindFormKey
        }
        if(extraForm.formKey&&extraForm.bindFormKey&&this.formKeyColumns[extraForm.formKey]&&this.formKeyColumns[extraForm.bindFormKey]){
          this.$nextTick(()=>{
            //关联关系
            let fields=[]
            this.formKeyColumns[extraForm.formKey].forEach(item => {
              let columnJson = JSON.parse(item.columnJson),
                field = {
                  "label": item.columnTitle,
                  "name": item.columnName,
                  "type": 'select',
                   searchable:true,
                   operators :['select_equals']
                };
                field.options=this.formKeyColumns[extraForm.bindFormKey].map(ite=>{
                    ite.value=ite.columnName,
                    ite.label=ite.columnTitle
                    return ite
                })
                fields.push(field)
            })
            extraForm.relevanceSchema.body[0].fields=fields
            //查询条件
            extraForm.conditionSchema.body[0].fields=getConditionsFields(this.formKeyColumns[extraForm.formKey])

            if(extraData){
              extraForm.relevanceSchema.data.conditions=extraData.relevance||{}
              extraForm.conditionSchema.data.conditions=extraData.conditions||{}
            }
          })
        }
        this.extraForms[index]=extraForm
        this.setFormKeyAndColumns()
      },


      setFormKeyAndColumns(){
        let extraFormKeys=this.extraForms.map(item=>{
           return item.formKey
        })
        this.$emit('setFormKeyAndColumns', {
          formKey:this.form.formKey,
          extraFormKeys,
          formColumns: this.formKeyColumns,
          primaryKeyFieldObj: this.primaryKeyFieldObj,
        })
      },

      submit() {
        this.extraFormValues=[]
        this.extraForms.forEach((item,index)=>{
          this.extraFormValues[index]={formKey:item.formKey,bindFormKey:item.bindFormKey}
          if(this.$refs.relevance){
            this.$refs.relevance[index].getValues('conditionsForm').then(res => {
              this.extraFormValues[index].relevance=res.conditions||{}
            })
            this.$refs.conditions[index].getValues('conditionsForm').then(res => {
              this.extraFormValues[index].conditions=res.conditions||{}
            })
          }
        })
        setTimeout(()=>{
          this.$refs.form.validate((valid) => {
            if (valid) {
              this.$emit('setValue', {
                tabType: 'basic',
                formData: {...this.form,extraForms:this.extraFormValues}
              })
            }
          });
        },100)
      },
      //增加附加表
      addExtra(develop) {
        this.extraForms.push({
          formKey: '',
          bindFormKey: '',
          relevanceSchema: {
            "type": "form",
            "name": 'conditionsForm',
            "data": {},
            "debug": false,
            "wrapWithPanel": false,
            "body": [{
              "type": "condition-builder",
              "name": "conditions",
              "builderMode": "simple",
              "showANDOR": true,
              "fields": [],
            }]
          },
          conditionSchema: {
            "type": "form",
            "name": 'conditionsForm',
            "data": {},
            "debug": false,
            "wrapWithPanel": false,
            "body": [{
              "type": "condition-builder",
              "name": "conditions",
              "fields": [],
            }]
          },
          develop,//展开显示
        })
      },
      delExtra(index){
        this.extraForms.splice(index,1)
        this.setFormKeyAndColumns()
      }
    }
  };
</script>
<style lang="scss" coped>
  .extra {
    border: 1px solid rgba(192, 196, 204, 0.25);
    margin-bottom: 20px;
    padding: 20px;
    border-radius: 10px;
    &-forms{
      display: flex;
      align-items: center;
      span,i{
        margin-left: 20px;
      }
    }
    .develop{
      cursor: pointer;
    }
  }

  .my-icon {
    cursor: pointer;
    font-size: 40px;
  }
</style>
